/**
 * @author GAX
 * @date 2025-09-05
 */
public class ProdConsumerDemo {
    public static void main(String[] args) {
        AirCondition airCondition = new AirCondition();

        // 2个生产者
        new Thread(()->{ for (int i = 0; i < 10; i++) {
            try {
                airCondition.increment();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        },"A1").start();
        new Thread(()->{ for (int i = 0; i < 10; i++) {
            try {
                airCondition.increment();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        },"A2").start();

        // 2个消费者
        new Thread(()->{ for (int i = 0; i < 10; i++) {
            try {
                airCondition.decrement();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        },"B1").start();
        new Thread(()->{ for (int i = 0; i < 10; i++) {
            try {
                airCondition.decrement();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        },"B2").start();
    }
}

// 创建一个资源类
class AirCondition {
    // 有一个初始值为 0 的变量
    private int number = 0;

    // 判断，干活，通知
    public synchronized void increment() throws InterruptedException {
        // ① 判断
        while (number != 0) {
            this.wait();
        }
        // ② 干活
        System.out.println(Thread.currentThread().getName() + "\t" + (++number));
        // ③ 通知
        this.notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
        while (number == 0) {
            this.wait();
        }
        System.out.println(Thread.currentThread().getName() + "\t" + (--number));
        this.notifyAll();
    }
}
